package com.sunkq.algorithms;

import org.junit.Test;

public class TreedNodeTest2 {

    public static void main(String[] args) {
        TreedNodeTest2 test = new TreedNodeTest2();
        TreeNode root = new TreeNode(9);
        root.right = new TreeNode(1);
        root.right.left = new TreeNode(2);
        root.right.right = new TreeNode(3);
        root.right.left.left = new TreeNode(4);
        root.right.left.right = new TreeNode(5);
//        System.out.println(test.diameterOfBinaryTree(root));
        test.flatten(root);
        while (root!=null){

            System.out.println(root.val);
            root = root.right;
        }
    }

    public void flatten(TreeNode root) {
        if(root == null){
            return;
        }
        flatten(root.left);
        flatten(root.right);

        TreeNode left = root.left;
        TreeNode right = root.right;

        root.left = null;
        root.right = left;

        TreeNode p = root;
        while (p.right!=null){
            p = p.right;
        }
        p.right = right;
    }


    int maxDiameter = 0;
    public int diameterOfBinaryTree(TreeNode root) {
        maxDep(root);
        return maxDiameter;
    }

    public int maxDep(TreeNode root){
        if(root==null){
            return 0;
        }
        int left = maxDep(root.left);
        int right = maxDep(root.right);
        int diameter = left + right;
        maxDiameter = Math.max(maxDiameter,diameter);
        return 1+Math.max(left,right);
    }
}

